package hot100;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class e2_合并区间 {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, Comparator.comparingInt(a -> a[0]));
        List<int[]> list = new ArrayList<>();
        for (int i = 0; i < intervals.length; i++) {
            if(list.isEmpty()){
                list.add(intervals[i]);
            }else {
                int toRight = list.get(list.size()-1)[1];
                int left = intervals[i][0];
                int right = intervals[i][1];
                if(toRight >= left){
                    list.get(list.size()-1)[1] = Math.max(toRight,right);
                }else {
                    list.add(intervals[i]);
                }
            }
        }
        return list.toArray(new int[list.size()][]);
    }
}
